package com.guoyw.seata.dubbo.order.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.guoyw.seata.dubbo.common.dto.AccountDTO;
import com.guoyw.seata.dubbo.common.dto.OrderDTO;
import com.guoyw.seata.dubbo.common.dubbo.AccountDubboService;
import com.guoyw.seata.dubbo.common.enums.RspStatusEnum;
import com.guoyw.seata.dubbo.common.response.ObjectResponse;
import com.guoyw.seata.dubbo.order.entity.TOrder;
import com.guoyw.seata.dubbo.order.mapper.TOrderMapper;
import com.guoyw.seata.dubbo.order.service.ITOrderService;
//import io.seata.spring.annotation.GlobalTransactional;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * author: guoyw
 * create: 2020-09-19 16:42
 **/
@Service
@Slf4j
public class ITOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements ITOrderService{
  
//  @Reference(version = "1.0.0")
  @Reference
  private AccountDubboService accountDubboService;
  
  /**
   * 创建订单
   * @Param:  OrderDTO  订单对象
   * @Return:  OrderDTO  订单对象
   */
  @Override
  @GlobalTransactional(name = "dubbo-gts-seata-example")
  public ObjectResponse<OrderDTO> createOrder(OrderDTO orderDTO){
    log.info("开始全局事务，XID = " + RootContext.getXID());
    ObjectResponse<OrderDTO> response = new ObjectResponse<>();
    //扣减用户账户
    AccountDTO accountDTO = new AccountDTO();
    accountDTO.setUserId(orderDTO.getUserId());
    accountDTO.setAmount(orderDTO.getOrderAmount());
    ObjectResponse objectResponse = accountDubboService.decreaseAccount(accountDTO);
  
    try{
      Thread.sleep(100);
    }catch(InterruptedException e){
      e.printStackTrace();
    }
  
    log.info("调用 减少账户余额服务："+objectResponse.getMessage());
    
    
    //生成订单号
    orderDTO.setOrderNo(UUID.randomUUID().toString().replace("-",""));
    //生成订单
    TOrder tOrder = new TOrder();
    BeanUtils.copyProperties(orderDTO,tOrder);
    tOrder.setCount(orderDTO.getOrderCount());
    tOrder.setAmount(orderDTO.getOrderAmount().doubleValue());
   
    baseMapper.createOrder(tOrder);
//    int a = 1/0;
    
    if (objectResponse.getStatus() != 200) {
      response.setStatus(RspStatusEnum.FAIL.getCode());
      response.setMessage(RspStatusEnum.FAIL.getMessage());
      return response;
    }
  
    response.setStatus(RspStatusEnum.SUCCESS.getCode());
    response.setMessage(RspStatusEnum.SUCCESS.getMessage());
    return response;
  }
}
